"""
Case Type   : SQL_LIMIT
Case Name   : 创建规则时，user设置为已存在的普通用户，规则只对该用户生效
Create At   : 2025/9/16
Owner       : lonely-dance
Description :
    1、修改参数;
    2、创建普通用户
    3、创建规则，user设置为已存在的普通用户
    4、使用被指定的用户执行被限流的sql
    5、使用未被指定的用户执行被限流的sql
    6、清理环境
Expect      :
    1、修改成功
    2、创建成功
    3、创建成功
    4、sql限流成功
    5、sql执行成功
    6、清理环境成功
History     :
"""

import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class SqlLimit(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----- {os.path.basename(__file__)} start-----')
        self.comm_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.standby_node = Node('Standby1DbUser')
        self.Constant = Constant()
        self.limit_name1 = 'limit0040_01'
        self.limit_name2 = 'limit0040_02'
        self.table_name1 = 'sql_limit0040_01'
        self.table_name2 = 'sql_limit0040_02'
        self.limit_id1 = 0

    def test_main(self):
        text = '----step1:修改参数enable_sql_limit=on expect:成功----'
        self.log.info(text)
        self.comm_sh.execute_gsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'enable_sql_limit = on')
        self.comm_sh.execute_gsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'instr_unique_sql_count = 1000')

        text = '----step2:创建普通用户 expect:成功----'
        self.log.info(text)
        cmd = f"create user {self.limit_name1} identified by '{macro.COMMON_PASSWD}';" \
              f"create user {self.limit_name2} identified by '{macro.COMMON_PASSWD}';"
        res = self.comm_sh.execut_db_sql(cmd)
        self.log.info(res)
        self.assertEqual(res.count('CREATE ROLE'), 2, '创建用户失败')

        text = '----step3:创建规则，user设置为已存在的普通用户 expect:成功----'
        self.log.info(text)
        cmd = f'''
        select gs_create_sql_limit('{self.limit_name1}','select',0,0,now(),'2035-3-30 23:59:59','{{{{select,from}}}}','','{{{{{self.limit_name1}}}}}');
        '''
        self.log.info(cmd)
        res = self.comm_sh.execut_db_sql(cmd)
        self.log.info(res)
        self.assertEqual('(1 row)', str(res.splitlines()[-1].strip()), '创建限流limit失败')
        self.limit_id1 = int(res.splitlines()[-2].strip())

        text = '----step4:使用被指定的普通用户执行被限流的sql expect:sql限流成功----'
        self.log.info(text)
        limit_sql_cmd = f'''
        source {macro.DB_ENV_PATH};
        gsql -d {self.pri_node.db_name} -p {self.pri_node.db_port} -U {self.limit_name1} -W {macro.COMMON_PASSWD} -c "
        create table {self.table_name1}(id int, name varchar);
        insert into {self.table_name1} values(1,'a');
        select * from {self.table_name1};
        drop table {self.table_name1};"
        '''
        self.log.info(limit_sql_cmd)
        res = self.pri_node.sh(limit_sql_cmd).result()
        self.log.info(res)
        self.assertIn('ERROR:  The request is over max concurrency of sql limit, the request will be rejected.', res,
                      '执行失败' + text)

        text = '----step5:使用未被指定的普通用户执行被限流的sql expect:sql限流成功----'
        self.log.info(text)
        limit_sql_cmd = f'''
        source {macro.DB_ENV_PATH};
        gsql -d {self.pri_node.db_name} -p {self.pri_node.db_port} -U {self.limit_name2} -W {macro.COMMON_PASSWD} -c "
        create table {self.table_name2}(id int, name varchar);
        insert into {self.table_name2} values(1,'a');
        select * from {self.table_name2};
        drop table {self.table_name2};"
        '''
        self.log.info(limit_sql_cmd)
        res = self.pri_node.sh(limit_sql_cmd).result()
        self.log.info(res)
        self.assertNotIn('ERROR', res, '执行失败' + text)

    def tearDown(self):
        text = '----step6:恢复环境 expect:成功----'
        self.log.info(text)
        cmd = f'select gs_delete_sql_limit({self.limit_id1});' \
              f'drop user if exists {self.limit_name1} CASCADE;' \
              f'drop user if exists {self.limit_name2} CASCADE;'
        res = self.comm_sh.execut_db_sql(cmd)
        self.log.info(res)
        self.comm_sh.execute_gsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'enable_sql_limit = off')
        self.comm_sh.execute_gsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'instr_unique_sql_count = 100')

        self.assertNotIn('ERROR', res, '执行失败' + text)
        self.log.info(f'----- {os.path.basename(__file__)} end-----')
